<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">专业：</span>
      <el-select
        v-model="params.majorName"
        placeholder="请输入或选择"
        clearable
        filterable
        @blur="selectBlur"
        @clear="selectClear"
        @change="selectChange"
      >
        <el-option
          v-for="(item, index) in majors"
          :key="index"
          :label="item.majorName"
          :value="item.majorName"
        />
      </el-select>
      <el-button type="primary" class="search-btn" @click="search"
        >查询</el-button
      >
    </div>
    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button @click="batchDelete">批量删除</el-button>
      <el-button @click="handleExportExcel">导出excel表</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="list"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="300"
        />
        <el-table-column label="学院" prop="collegeName" />
        <el-table-column label="专业" prop="majorName" />
        <el-table-column label="操作" fixed="right" width="90">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="
                edit(
                  scope.row.majorId,
                  scope.row.collegeName,
                  scope.row.majorName
                )
              "
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="deleteOne(scope.row.majorId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加或修改操作日志记录对话框 -->
    <el-dialog :visible.sync="open" width="500px" append-to-body>
      <span slot="title">{{
        Form.majorId ? "修改专业信息" : "添加专业信息"
      }}</span>
      <el-form ref="form" :model="Form" :rules="Rules" label-width="80px">
        <el-form-item label="学院" prop="colleges">
          <el-select v-model="Form.collegeId">
            <el-option
              v-for="item in colleges"
              :key="item.collegeId"
              :value="item.collegeId"
              :label="item.collegeName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业名称" prop="majorName">
          <el-input v-model="Form.majorName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {
  getAllMajorsByPageAPI,
  getAllMajorsAPI,
  addOrEditMajorAPI,
  deleteMajorAPI,
  exportExcelAPI
} from "@/api/majors";
import { getAllCollegesAPI } from "@/api/colleges";

export default {
  name: "Check_results",
  data() {
    return {
      Rules: {
        majorName: [
          {
            required: true,
            message: "请输入专业",
            trigger: "blur",
          },
        ]
      },
      Form: {
        majorId: "",
        majorName: "",
        collegeId: "",
      },
      colleges: [],
      open: false,
      selecttionVal: [],
      majors: [],
      total: 0, //页总数
      list: [], //列表
      params: {
        //参数
        page: 1,
        pageSize: 2,
        majorName: "",
      },
    };
  },
  created() {
    this.getAllMajorsByPage();
    this.getAllMajors();
    this.getAllColleges();
  },
  methods: {
    handleExportExcel() {
      exportExcelAPI(this.params)
        .then(response => {
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = 'scores.xlsx';
          link.click();

          window.URL.revokeObjectURL(link.href);
        })
        .catch(error => {
          console.error('Failed to export Excel:', error);
        });
    },
    //获取学院数据
    async getAllColleges() {
      const res = await getAllCollegesAPI();
      this.colleges = res.data;
    },
    //单个删除
    deleteOne(id) {
      this.$confirm("您确定要删除此数据吗?", "提示")
        .then(async () => {
          // console.log('点击确定');
          await deleteMajorAPI(id);
          this.$message.success("删除成功");
          if (this.list.length == 1 && this.params.page > 1) {
            this.params.page--;
          }
          this.getAllMajors();
          this.getAllMajorsByPage();
        })
        .catch(() => {});
    },
    //批量删除
    batchDelete() {
      if (this.selecttionVal.length <= 0) {
        this.$message.warning("请先选择要删除的数据");
        return;
      }
      const ids = this.selecttionVal.map((item) => {
        return item.majorId;
      });
      this.$confirm("您确定要删除此数据吗?", "提示")
        .then(async () => {
          await deleteMajorAPI(ids.join(","));
          this.$message.success("批量删除成功");
          this.getAllMajors();
          if (
            this.list.length == this.selecttionVal.length &&
            this.params.page > 1
          ) {
            this.params.page--;
          }
          this.getAllMajorsByPage();
        })
        .catch(() => {});
    },
    //获取选择的数据
    handleSelectionChange(val) {
      this.selecttionVal = val;
    },
    //提交表格
    submitForm() {
      this.$refs.form.validate(async (flag) => {
        if (!flag) return;
        if (this.Form.majorId != "") {
          //修改操作
          await addOrEditMajorAPI(this.Form);
          this.$message.success("修改成功");
          this.getAllMajors();
        } else {
          //新增操作
          await addOrEditMajorAPI(this.Form);
          this.$message.success("添加成功");
          this.getAllMajors();
          this.reset()
          this.params.page = 1;
        }
        this.open = false;
        this.getAllMajorsByPage();
      });
    },
    //编辑按钮
    async edit(majorId, collegeName, majorName) {
      this.Form.majorId = majorId;
      //找到学院名称对应的学院Id
      const college = this.colleges.find(
        (item) => item.collegeName === collegeName
      );
      this.Form.collegeId = college.collegeId;
      this.Form.majorName = majorName;
      this.open = true;
    },
    // 表单重置
    reset() {
      this.Form.majorName = "";
      this.Form.collegeId = "";
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.Form.collegeId = this.colleges[0].collegeId
      if (this.Form.majorId) {
        this.Form.majorId = "";
        this.Form.majorName = "";
        this.Form.collegeId = this.colleges[0].collegeId
      }
      this.open = true;
    },
    //获取专业分页数据
    async getAllMajorsByPage() {
      const res = await getAllMajorsByPageAPI(this.params);
      this.total = res.data.total;
      this.list = res.data.records;
    },
    //获取专业列表
    async getAllMajors() {
      const res = await getAllMajorsAPI();
      this.majors = res.data;
    },
    //多选框输入值
    selectBlur(e) {
      // 意见类型
      if (e.target.value !== "") {
        this.params.majorName = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    },
    //清空多选框
    selectClear() {
      this.params.majorName = "";
      this.$forceUpdate();
    },
    //改变多选框
    selectChange(val) {
      this.params.majorName = val;
      this.$forceUpdate();
    },
    //点击查询按钮
    search() {
      this.params.page = 1;
      this.getAllMajorsByPage();
    },
    //计算序号
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1;
    },
    //页数改变
    handleCurrentChange(val) {
      this.params.page = val;
      this.getAllMajorsByPage();
    },
    //页条数改变
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getAllMajorsByPage();
    },
  },
};
</script>


<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>